Functions
fn main() {
print_labeled_measurement(5, 'h');
}
fn print_labeled_measurement(value: i32, unit_label: char) {
println!("The measurement is: {value}{unit_label}");
}
Declaration
-
You must declare the type of each parameter.
-
Rust doesn’t care where you define your functions, only that they’re defined somewhere in a scope that can be seen by the caller.
Return
fn five() -> i32 {
5
}
fn main() {
let x = five();
println!("The value of x is: {x}");
}
-
If there is a return, the return type must be specified.
-
Using the
returnkeyword is not necessary. -
If
returnis omitted, do not use a;on the return line.
Getters
-
Often, but not always, when we give a method the same name as a field we want it to only return the value in the field and do nothing else. Methods like this are called getters , and Rust does not implement them automatically for struct fields.
-
Getters are useful because you can make the field private but the method public, and thus enable read-only access to that field as part of the type’s public API.
Closures
-
Definition :
-
They are anonymous functions that capture and use variables from the scope where they were defined.
-
-
GDScript :
-
Exactly the same as GDScript. In GDScript, anonymous functions are all closures.
-
-
Uses
||. -
Example:
let mut list = vec![1, 2, 3]; println!("Before defining closure: {list:?}"); let mut borrows_mutably = || list.push(7); borrows_mutably(); println!("After calling closure: {list:?}");-
Output:
Before defining closure: [1, 2, 3] After calling closure: [1, 2, 3, 7]
-